﻿using System.Collections.Generic;
using System.Linq;
using compshop.Modules.DepartmentList.View;
using compshop.Infrastructure;
using compshop.Infrastructure.CompShopDataService;

namespace compshop.Modules.DepartmentList.Presenter
{
    public class DepartmentListPresenter
    {
        private CompShopEntities contextDS;       
        private EventsManager eventsManager;
        private IList<Department> _departments;

        public IViewDepartmentList View { set; get; }

        public DepartmentListPresenter(EventsManager eventsManager)
        {
            contextDS = CompShopEntitiesContext.GetInstance();
            this.eventsManager = eventsManager;
            eventsManager.departmentListPresenter = this;
            _departments = GetDepartments();
        }

        public IList<Department> Departments 
        {
            set { _departments = value; }
            get { return _departments; }
        }

        public IList<Department> GetDepartments()
        {
            List<Department> list = contextDS.Departments.ToList();
            foreach (Department d in list)
                d.Employees.Load(contextDS.Employees.Where(x => x.DepartmentID == d.DepartmentID));
            return list;
        }

        public void ShowDepartmentDialog(Department department)
        {
            DepartmentDialog dialog = new DepartmentDialog(department);
            if (dialog.ShowDialog() == true)
            {
                try
                {
                    if (dialog.Department.DepartmentID == 0)
                    {
                        contextDS.AddToDepartments(dialog.Department);
                        Departments.Add(dialog.Department);
                    }
                    else
                        contextDS.UpdateObject(dialog.Department);
                    contextDS.SaveChanges();
                    View.UpdateData();
                }
                catch (System.Exception ex)
                {
                    System.Windows.MessageBox.Show(Resource.msgSaveToDBError+"\n"+ex.Message);
                }
            }
        }

      
        #region Publishers
        public void onSelectedDepartment(int id)
        {
            eventsManager.eventAggregator.GetEvent<DepartmentSelectedEvent>().Publish(id);
        }
        #endregion

        #region Handlers
        public void SetSelectedDepartment(int id)
        {

        }
        #endregion

    }
}
